package com.love.web.session.filter;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;

public class MyHttpServletRequest extends HttpServletRequestWrapper{
	
	private HttpServletRequest request;
	private HttpServletResponse response;
	private Manager manager;
	private HttpSession httpSession;
	
	public MyHttpServletRequest(HttpServletRequest request, HttpServletResponse response, Manager manager){
		super(request);
		this.request = request;
		this.response = response;
		this.manager = manager;
	}
	
	@Override
	public HttpSession getSession() {
		return getSession(true);
	}

	@Override
	public HttpSession getSession(boolean create) {
		if(httpSession != null){
			return httpSession;
		}
		if(this.manager != null){
			httpSession = manager.findSession(getSessionId());
			if(httpSession != null){
				return httpSession;
			}else{
				if(create){
					httpSession = manager.createEmptySession();
				}
				return httpSession;
			}
		}
		return super.getSession(create);
	}
	
	private String getSessionId(){
		if(request.getCookies() == null){
			return null;
		}
		for (Cookie item : request.getCookies()) {
			if(StringUtils.equals(item.getName(), SessionConstants.SESSION_ID_COOKIE)){
				return item.getValue();
			}
		}
		return null;
	} 

	public void endAccess(){
		HttpSession session = getSession();
		manager.saveSession(session.getId(), (Session)session);
	}
	
}
